<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Admin\Models\Member;
use App\Services\Common;
use App\Services\Store;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Ixudra\Curl\Facades\Curl;
use DB;

class MemberController extends Controller
{
	use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('会员')
            ->description('列表')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('会员')
            ->description('详细')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('会员')
            ->description('编辑')
            ->body($this->form($id)->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('会员')
            ->description('创建')
            ->body($this->form());
    }

//  public function update(Request $request, $id)
//  {
//
//  }

//  /**
//   * Handle update.
//   *
//   * @param int $id
//   *
//   * @return \Symfony\Component\HttpFoundation\Response
//   */
//  public function update($id, $data = null)
//  {
//
//      return $this->returnMsg(1, $id);
//  }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Member);

        $grid->muId('ID');
        $grid->muNickName('姓名');
        $grid->muSex('性别')->using(['0' => '女', '1' => '男']);
        $grid->muMobile('手机号');
        $grid->alName('身份');
        $grid->muReferrerName('推荐人');
        $grid->waMoney('账户金额')->display(function($waMoney) {
		    return "<a href='./myTrade?userCode={$this->muCode}'>{$waMoney}</a>";
		});
//      $grid->muPoints('积分');

        $grid->muTotalExpend('总消费');
        $grid->createTime('登记时间');


		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();

		});

		$grid->actions(function ($actions) {
		    // $actions->disableDelete();
//		    $actions->disableEdit();
//		    $actions->disableView();
			// prepend一个操作
    		//$actions->prepend("<a class='btn btn-dropbox' href='".route('cardUseList')."?muCode={$actions->row->muCode}'>服务历史</a>");
    		$actions->prepend('<a href="'.route('cardUseList').'?muCode='.$actions->row->muCode.'" class="btn btn-info btn-sm" style="margin-right: 5px;">卡项历史</a>');
		});

		$grid->tools(function (Grid\Tools $tools){

		    $tools->append('<a class="btn btn-sm btn-danger form-history-bac" style="float: right;margin-right: 20px;" href="'.route('chargeView').'"><i class=""></i>&nbsp;会员充值</a>');
		});

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();

		    $filter->column(1/2, function ($filter) {
				$filter->like('muNickName', '姓名');
				$formartData = array();
	            $formartData[0] = '女';
	            $formartData[1] = '男';
	            $filter->equal('muSex', '性别')->select($formartData);
			});

			$filter->column(1/2, function ($filter) {
				$filter->like('muMobile', '手机号');
				//$filter->equal('muAccount', '店名');
//				$filter->gt('muAccount', '账户余额');
//				$filter->gt('muPoints', '积分');
//			    $filter->gt('muTotalExpend', '总消费');
			});

		});

		// 默认展开筛选框
		$grid->expandFilter();

		// 禁用行选择checkbox
		$grid->disableRowSelector();

		// 禁用导出
		$grid->disableExport();
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
    	$Member = new Member();
        $show = new Show($Member->findOrFail($id));

        $show->muId('ID');
        $show->muCode('用户码');
        $show->muNickName('姓名');
//      $show->muRealName('姓名');
        $show->muSex('性别')->using(['0' => '女', '1' => '男']);;
        $show->muMobile('手机号');
        $show->muMemo('备注');
//      $show->muAccount('账户金额');
        $show->muPoints('积分');
        $show->muTotalExpend('总消费');
        $show->createTime('创建时间');
        $show->updateUser('最后修改人');
        $show->updateTime('最后修改时间');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($id=false)
    {
        return Admin::Form(Member::class, function (Form $form) use($id) {

			$form->hidden('muId');
			$form->hidden('createUser')->value(isset($_GET['back'])?$_GET['back']:"");
			$form->text('muNickName', '姓名')->rules("required", ['required' => '请填写用户姓名']);
//			$form->text('muRealName', '姓名');
   //          $form->text('muCardNum', '卡号');
			$form->radio('muSex', '性别')->options(['0' => '女', '1'=> '男'])->default(0);
   //          $form->date('muBirthday', '生日');
            //A、B、AB和O血型之外,还有Rh阳性、Rh阴性
            // $form->select('muBloodType', '血型')
                // ->options(['A'=>'A','B'=>'B','AB'=>'AB','O'=>'O','Rh阳'=>'Rh阳','Rh阴'=>'Rh阴']);
			$form->mobile('muMobile', '电话')->attribute(['style' => 'width: 25%']);
                 //                            ->rules('regex:/^$|^[1][0-9]{10}$/', [
        									// 'regex' => '手机号格式不正确'
        									// ])

            $form->text('muAddress', '地址');
            if (Admin::user()->isRole('manager')){
                $form->select('alId', '身份')->options($this->getAgencyLevelSelect())->rules("required", ['required' => '请选择用户身份']);
            }else{
                $form->select('alId', '身份')->options($this->getAgencyLevelSelect())->rules("required", ['required' => '请选择用户身份'])->readOnly()->help('只有店长可以更改身份');
            }

        	$Store = new Store();
        	$sId = Admin::user()->sId;
        	//print_r($Store->getUserTags($sId));exit;
        	$form->multipleSelect('muTags', '标签')->options($Store->getUserTags($sId));
        	$form->textarea('muMemo', '备注');
//      	$form->number('mlId', '等级');
            if (Admin::user()->isRole('manager')){
                $form->select('muReferrerId', '推荐人')->options($this->getReferrerSelect());
            }else{
                $form->select('muReferrerId', '推荐人')->options($this->getReferrerSelect())->readOnly()->help('只有店长可以更改推荐人');
            }

			$form->hidden('muCode')->default($this->create_guid());

            $form->tools(function (Form\Tools $tools) {

			    // 去掉`列表`按钮
//			    $tools->disableList();

			    // 去掉`删除`按钮
			    $tools->disableDelete();

			    // 去掉`查看`按钮
//			    $tools->disableView();

			    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
//			    $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
			});

			$form->footer(function ($footer) {

//			    // 去掉`重置`按钮
//			    $footer->disableReset();
//
//			    // 去掉`提交`按钮
//			    $footer->disableSubmit();

			    // 去掉`查看`checkbox
			    $footer->disableViewCheck();

			    // 去掉`继续编辑`checkbox
			    $footer->disableEditingCheck();

			    // 去掉`继续创建`checkbox
//			    $footer->disableCreatingCheck();

			});

			//保存后回调
			$form->saved(function (Form $form) {
				$sId = Admin::user()->sId;


                // 绑定关系
                $username = Admin::user()->name;
                $host = config('admin.dataApiHost');
                $url = $host.'/distributionUsers/boundRelation';
                $data = array();
                $data['dcKey'] = $sId;
                $data['uId'] = $form->model()->muCode;
                $data['parentId'] = $form->model()->muReferrerId;
                $data['operationUser'] = $username;
                if ($form->model()->muId){
                    $data['change'] = true;
                }else{
                    $data['change'] = false;
                }

                $response = Curl::to($url)
                	->withData($data)
                	->post();

				$muNum = DB::table('member_users')->where('mcId', $sId)->count();
				DB::table('store')->where('sId', $sId)->update(['sMemberNum'=>$muNum]);


				if ($form->createUser == 'storegoodsout'){
					// 跳转页面
					return redirect('admin/storegoodsout/create');
				}
			});
        });
    }

    // 获取区域列表下拉框数据
    public function getAreaSelectData($parentCode=''){

		if (isset($_GET['q'])){
			$parentCode = $_GET['q'];
		}
    	$Common = new Common();
    	$baseData = $Common->getAreaList($parentCode);

    	if (isset($_GET['q'])){
    		return $baseData;
    	}
    	$selectData = array();
    	foreach($baseData as $info){
    		$selectData[$info['areaCode']] = $info['areaName'];
    	}

    	return $selectData;
    }

    public function chargeView(Content $content){

    	$chargeForm = Admin::Form(Member::class, function (Form $form) {

			$form->select('muCode', '购买会员')->options($this->getUserSelect())->rules("required", ['required' => '请选择充值会员']);;
			$form->number('chargeMoney', '充值金额')->default(12800)->rules("required", ['required' => '请填写充值金额']);
			$form->select('payWay', '支付方式')->options(array('现金' => '现金', '支付宝' => '支付宝', '微信' => '微信'))->rules("required", ['required' => '请选择支付方式']);

            $form->tools(function (Form\Tools $tools) {

			    // 去掉`列表`按钮
//			    $tools->disableList();

			    // 去掉`删除`按钮
			    $tools->disableDelete();

			    // 去掉`查看`按钮
//			    $tools->disableView();

			    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
//			    $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
			});

			$form->footer(function ($footer) {

//			    // 去掉`重置`按钮
//			    $footer->disableReset();
//
//			    // 去掉`提交`按钮
//			    $footer->disableSubmit();

			    // 去掉`查看`checkbox
			    $footer->disableViewCheck();

			    // 去掉`继续编辑`checkbox
			    $footer->disableEditingCheck();

			    // 去掉`继续创建`checkbox
//			    $footer->disableCreatingCheck();

			});
        });

        return $content->header('会员')->description('充值')->body($chargeForm);
    }

    private function getAgencyLevelSelect(){

		$sId = Admin::user()->sId;
		$host = config('admin.dataApiHost');
		$url = $host.'/agencyLevel/getList?acKey='.$sId;

		$data = Curl::to($url)->get();

		$data = json_decode($data, true);
		$infoList = $data['data']['data'];

		$selectData = array();
		foreach($infoList as $info){
			$selectData[$info['alId']] = $info['alName'];
		}

		return $selectData;
	}

	private function getReferrerSelect(){

		$userModel = config('admin.database.users_model');

		$sId = Admin::user()->sId;

        $userM = new $userModel();
		$userList = $userM->where('sId', $sId)->get();
//		print_r($userList);exit;
		$selectData = array();
		foreach($userList as $info){
			$selectData[$info['auCode']] = $info['name'];
		}

        $host = config('admin.dataApiHost');
        $sId = Admin::user()->sId;
        $url = $host . "/member/getList?mcKey={$sId}&page=1&perPage=1000&all=1";
        $rst = Curl::to($url)->get();
        $user = json_decode($rst, true);
        if(!empty($user['data']['data'])){
            $list = $user['data']['data'];
            foreach($list as $info){
                $selectData[$info['muCode']] = $info['muRealName'];
            }
        }

		return $selectData;
	}

	private function create_guid() {
		$charid = md5(uniqid(mt_rand(), true));
		$hyphen = chr(45);// "-"
		$uuid = substr($charid, 0, 8)
				.substr($charid, 8, 4)
				.substr($charid,12, 4)
				.substr($charid,16, 4)
				.substr($charid,20,12);
		return $uuid;
	}

	// 获取会员下拉框
    private function getUserSelect(){
    	$sId = Admin::user()->sId;
		$host = config('admin.dataApiHost');
		$url = $host.'/member/getList?mcKey='.$sId.'&page=1&perPage=999';

		$data = Curl::to($url)->get();

		$data = json_decode($data, true);
		$infoList = $data['data']['data'];

		$selectData = array();
		foreach($infoList as $info){
			$selectData[$info['muCode']] = $info['muRealName']?$info['muRealName']:$info['muNickName'].'|'.$info['muMobile'];
		}

		return $selectData;
    }
}
